﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wicresoft.UnifyShow.Business;
using System.Configuration;
using Microsoft.Practices.Unity;
using Wicresoft.UnifyShow.BusinessImpl;

namespace Wicresoft.UnifyShow2.Portal.Controllers
{
    [Authorize]
    public class NavigateController : BaseController
    {
        IUser_X user_x;
        IPlanManagement _plan;
        IItsmEventType _itsm;
        IAlert _alert;
        ICommonResource _resource;
        //
        // GET: /Navigate/
        protected override void Dispose(bool disposing)
        {
            ((IDisposable)user_x).Dispose();
            ((IDisposable)_plan).Dispose();
            ((IDisposable)_itsm).Dispose();
            ((IDisposable)_alert).Dispose();
            ((IDisposable)_resource).Dispose();
        }

        [InjectionConstructor]
        public NavigateController(IUser_X _user_x, IPlanManagement plan, IItsmEventType itsm, IAlert alert, ICommonResource resource)
        {
            user_x = _user_x;
            _plan = plan;
            _itsm = itsm;
            _alert = alert;
            _resource = resource;
        }

        public ActionResult Index()
        {
            SetRoles(user_x);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            var site = user_x.GetSiteBranchByID(USER_X.ID).FirstOrDefault(x => x.Name == USER_X.Company);
            if (site == null)
                throw new Exception("UserSite is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            //获取电子公告
            decimal totalCount = 0;
            var bullentin = _plan.GetAllAnnouncement(out totalCount, null, null, true, "BeginTime");
            if (bullentin.Count > 0)
            {
                bullentin = bullentin.Take(5).ToList();
            }
            ViewData["Announcement"] = bullentin;
            ViewData["AnnouncementCount"] = totalCount;

            //获取值班计划
            IDutyPlan _dutyPlan = new DutyPlan();
            ViewData["HasTodayDuty"] = _dutyPlan.IsExist(DateTime.Today.Date, site.ID);

            //获取常用资源
            decimal rtotalCount = 0;
            var myResource = _resource.GetAllCommonResources(out rtotalCount, null, null, "CREATETIME");
            if (myResource.Count > 0)
            {
                myResource = myResource.Take(5).ToList();
            }
            ViewData["CommonResources"] = myResource;
            ViewData["ResourceCount"] = rtotalCount;

            //获取运维报告
            decimal opstotalCount = 0;
            var myOps = _resource.GetAllOpsDocuments((site.ID).ToString(), out opstotalCount, null, null, "CREATETIME");
            if (myOps.Count > 0)
            {
                myOps = myOps.Take(5).ToList();
            }
            ViewData["OpsResources"] = myOps;
            ViewData["OpsCount"] = opstotalCount;


            return View();
        }

        /// <summary>
        /// 今日运维
        /// </summary>
        /// <returns></returns>
        public ActionResult Maintenance()
        {
            SetRoles(user_x);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            var site = user_x.GetSiteBranchByID(USER_X.ID).FirstOrDefault(x => x.Name == USER_X.Company);
            if (site == null)
                throw new Exception("UserSite is null.");
            ViewBag.UserDept = USER_X.Department;
            ViewBag.UserCompany = USER_X.Company;

            //不是省局信息中心的人 首页进去 个人工作台
            if (!(string.Equals(USER_X.Company.Trim(), "福建省烟草专卖局") && string.Equals(USER_X.Department.Trim(), "经济信息中心")))
            {
                return RedirectToAction("Index");
            }

            //获取电子公告
            decimal totalCount = 0;
            var bullentin = _plan.GetAllAnnouncement(out totalCount, null, null, true, "BeginTime");
            if (bullentin.Count > 0)
            {
                bullentin = bullentin.Take(5).ToList();
            }
            ViewData["Announcement"] = bullentin;
            ViewData["AnnouncementCount"] = totalCount;

            //获取值班计划
            IDutyPlan _dutyPlan = new DutyPlan();
            ViewData["HasTodayDuty"] = _dutyPlan.IsExist(DateTime.Today.Date, site.ID);

            //获取常用资源
            decimal rtotalCount = 0;
            var myResource = _resource.GetAllCommonResources(out rtotalCount, null, null, "CREATETIME");
            if (myResource.Count > 0)
            {
                myResource = myResource.Take(5).ToList();
            }
            ViewData["CommonResources"] = myResource;
            ViewData["ResourceCount"] = rtotalCount;

            //获取运维报告
            decimal opstotalCount = 0;
            var myOps = _resource.GetAllOpsDocuments((site.ID).ToString(), out opstotalCount, null, null, "CREATETIME");
            if (myOps.Count > 0)
            {
                myOps = myOps.Take(5).ToList();
            }
            ViewData["OpsResources"] = myOps;
            ViewData["OpsCount"] = opstotalCount;


            return View();
        }

        [HttpPost]
        public JsonResult toDoWorkList()
        {
            int pageIndex, pageSize;
            if (int.TryParse(Request.Form["page"], out pageIndex) == false || int.TryParse(Request.Form["rows"], out pageSize) == false)
            {
                throw new Exception("获取页面信息失败");
            }
            var sortitem = Request.Form["sort"];
            var sortorder = Request.Form["order"];
            demoModel model = new demoModel();

            model.rows = ToDoHelper.GetListToDo(User.Identity.Name, out model.total, pageIndex, pageSize, sortitem, sortorder);
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult DoingWorkList()
        {
            int pageIndex, pageSize;
            if (int.TryParse(Request.Form["page"], out pageIndex) == false || int.TryParse(Request.Form["rows"], out pageSize) == false)
            {
                throw new Exception("获取页面信息失败");
            }
            var sortitem = Request.Form["sort"];
            var sortorder = Request.Form["order"];
            demoModel model = new demoModel();

            model.rows = ToDoHelper.GetListDoing(User.Identity.Name, out model.total, pageIndex, pageSize, sortitem, sortorder);
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        ///  计划运维一览
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="sort"></param>
        /// <param name="order"></param>
        /// <param name="Type"></param>
        /// <returns></returns>
        public JsonResult MaintenanceTaskList(int page, int rows, string sort, string order, string Type)
        {
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            var site = user_x.GetSiteBranchByID(USER_X.ID).FirstOrDefault(x => x.Name == USER_X.Company);
            if (site == null)
                throw new Exception("UserSite is null.");

            decimal count = 0;

            if (string.IsNullOrEmpty(sort)) { sort = "CreateTime"; }
            if (string.Equals(sort, "CreateUserName")) { sort = "CreateUserID"; }
            if (string.Equals(sort, "UpdateUserName")) { sort = "UpdateUserID"; }
            if (string.IsNullOrEmpty(order)) { order = "Descending"; }

            var list = new List<TaskModel>();

            //今日新增
            if (Type.Equals("Today", StringComparison.OrdinalIgnoreCase))
            {
                list = _plan.GetTaskCreateInToday(site.ID, page, rows, out count, sort, order);
            }
            //未关闭
            else
            {
                list = _plan.GetTaskNotComplete(site.ID, page, rows, out count, sort, order);
            }

            foreach (var item in list)
            {
                var creator = user_x.GetUserByID(item.CreateUserID);
                if (creator != null)
                {
                    item.CreateUserName = creator.DisplayName;
                }

                var updator = user_x.GetUserByID(item.UpdateUserID);
                if (updator != null)
                {
                    item.UpdateUserName = updator.DisplayName;
                }
            }

            return Json(new { rows = list, total = count }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 工单运维一览
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="sort"></param>
        /// <param name="order"></param>
        /// <param name="Type"></param>
        /// <returns></returns>
        public JsonResult MaintenanceWorkOrderList(int page, int rows, string sort, string order, string Type)
        {
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            var site = user_x.GetSiteBranchByID(USER_X.ID).FirstOrDefault(x => x.Name == USER_X.Company);
            if (site == null)
                throw new Exception("UserSite is null.");

            decimal count = 0;

            if (string.IsNullOrEmpty(sort)) { sort = "SubmitDate"; }
            if (string.IsNullOrEmpty(order)) { order = "Descending"; }

            var list = new List<ToDoModel>();

            if (Type.Equals("Today", StringComparison.OrdinalIgnoreCase))
            {
                list = _itsm.GetWorkOrderCreateInToday(site.Name, out count, page, rows, sort, order);
            }
            else
            {
                list = _itsm.GetNotClosedWorkOrderBeforeToday(site.Name, out count, page, rows, sort, order);
            }

            return Json(new { rows = list, total = count }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 告警运维一览
        /// </summary>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        /// <param name="sort"></param>
        /// <param name="order"></param>
        /// <param name="Type"></param>
        /// <returns></returns>
        public JsonResult MaintenanceAlertList(int page, int rows, string sort, string order, string Type)
        {
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            var site = user_x.GetSiteBranchByID(USER_X.ID).FirstOrDefault(x => x.Name == USER_X.Company);
            if (site == null)
                throw new Exception("UserSite is null.");

            decimal count = 0;

            if (string.IsNullOrEmpty(sort)) { sort = "CreateTime"; }
            if (string.IsNullOrEmpty(order)) { order = "Descending"; }

            var list = new List<AlertDetailAndDevice>();

            if (Type.Equals("Today", StringComparison.OrdinalIgnoreCase))
            {
                list = _alert.GetAlertCreateInToday((int)site.ID, out count, page, rows, sort, order);
            }
            else
            {
                list = _alert.GetNoClosedAlert((int)site.ID, out count, page, rows, sort, order);
            }

            return Json(new { rows = list, total = count }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetURL(string type, string operation, string requestid)
        {
            string url = string.Empty;
            if (!string.IsNullOrEmpty(type))
            {
                if (type.Equals("自服务"))
                {
                    url = string.Format(ConfigurationManager.AppSettings["SelfRequestUrl"], requestid);
                }
                else if (type.Equals("事件"))
                {
                    url = string.Format(ConfigurationManager.AppSettings["ITSMRequestUrl"], "HPD:Help Desk", requestid);
                }
                else if (type.Equals("变更"))
                {
                    if (operation == "审批")
                    {
                        url = ConfigurationManager.AppSettings["ApprovalCenter"];
                    }
                    else
                    {
                        url = string.Format(ConfigurationManager.AppSettings["ITSMRequestUrl"], "CHG:Infrastructure Change", requestid);
                    }
                }
                else if (type.Equals("知识"))
                {
                    url = ConfigurationManager.AppSettings["ApprovalCenter"];
                }
                else if (type.Equals("问题"))
                {
                    url = string.Format(ConfigurationManager.AppSettings["ITSMRequestUrl"], "PBM:Problem Investigation", requestid);
                }
                else if (type.Equals("任务"))
                {
                    url = string.Format(ConfigurationManager.AppSettings["ITSMRequestUrl"], "TMS:Task", requestid);
                }
            }
            return Json(Server.UrlEncode(url), JsonRequestBehavior.AllowGet);
        }

        public JsonResult quickAccess()
        {
            //get user info
            var USER_X = user_x.GetUser_XByName(User.Identity.Name);
            if (USER_X == null)
                throw new Exception("USER_X is null.");
            var sites = user_x.GetSiteBranchByID(USER_X.ID);


            JsonCollection root = new JsonCollection();

            //sso url
            //Url.Action("SSO","Account",new { redirectionUrl= }）

            //ITSM入口节点
            //ConfigurationManager.AppSettings["ITSMURL"]
            JsonObject itsm = new JsonObject();
            itsm.MergeProperty("text", new JsonConstant("ITSM子系统"));
            itsm.MergeProperty("iconCls", new JsonConstant("icon-redo"));
            JsonObject attr = new JsonObject();
            attr.MergeProperty("sso", new JsonConstant(Url.Action("SSO", "Account", new { redirectionUrl = ConfigurationManager.AppSettings["ITSMURL"] })));
            itsm.MergeProperty("attributes", attr);
            root.AppendObject(itsm);

            if (USER_X.Department != "中软海晟技术支持组")
            {
                //自服务入口节点
                JsonObject self = new JsonObject();
                self.MergeProperty("text", new JsonConstant("自服务子系统"));
                self.MergeProperty("iconCls", new JsonConstant("icon-redo"));
                JsonObject attr2 = new JsonObject();
                attr2.MergeProperty("sso", new JsonConstant(Url.Action("SSO", "Account", new { redirectionUrl = ConfigurationManager.AppSettings["SelfUrl"] })));
                self.MergeProperty("attributes", attr2);
                root.AppendObject(self);
            }
            if (sites != null && sites.Count > 0 && sites.FirstOrDefault(s => s.Name == USER_X.Company) != null)
            {
                var t = sites.FirstOrDefault(s => s.Name == USER_X.Company);
                if (USER_X.Department != "中软海晟技术支持组")
                {
                    //监控管理平台节点
                    JsonObject monitor = new JsonObject();
                    monitor.MergeProperty("id", new JsonConstant("monitor"));
                    monitor.MergeProperty("text", new JsonConstant("监控管理子系统"));
                    monitor.MergeProperty("iconCls", new JsonConstant("icon-redo"));
                    JsonObject attr3 = new JsonObject();
                    //attr3.MergeProperty("sso", new JsonConstant(Url.Action("SSO", "Account", new { redirectionUrl = t.GJ_IPPort1 })));
                    attr3.MergeProperty("sso", new JsonConstant(t.GJ_IPPort1));
                    attr3.MergeProperty("userdept", new JsonConstant(USER_X.Department));
                    attr3.MergeProperty("usercompany", new JsonConstant(USER_X.Company));
                    monitor.MergeProperty("attributes", attr3);
                    root.AppendObject(monitor);
                }

                //报表管理平台节点
                JsonObject report = new JsonObject();
                report.MergeProperty("id", new JsonConstant("report"));
                report.MergeProperty("text", new JsonConstant("报表"));
                report.MergeProperty("iconCls", new JsonConstant("icon-redo"));
                JsonObject attr4 = new JsonObject();
                attr4.MergeProperty("sso", new JsonConstant(ConfigurationManager.AppSettings["ReportURL"]));
                attr4.MergeProperty("siteid", new JsonConstant(t.ID));
                attr4.MergeProperty("userdept", new JsonConstant(USER_X.Department));
                attr4.MergeProperty("usercompany", new JsonConstant(USER_X.Company));
                //attr4.MergeProperty("sso", new JsonConstant(Url.Action("SSO", "Account", new { redirectionUrl = ConfigurationManager.AppSettings["ReportURL"] })));
                report.MergeProperty("attributes", attr4);
                root.AppendObject(report);

                //省局信息中心添加“统一展示”入口
                if (t.Alias.Equals("省局") && USER_X.Department.Equals("经济信息中心"))
                {
                    JsonObject showview = new JsonObject();
                    showview.MergeProperty("id", new JsonConstant("showView"));
                    showview.MergeProperty("text", new JsonConstant("统一展示"));
                    showview.MergeProperty("iconCls", new JsonConstant("icon-redo"));
                    JsonObject attr_view = new JsonObject();
                    attr_view.MergeProperty("sso", new JsonConstant(ConfigurationManager.AppSettings["ShowViewUrl"]));
                    showview.MergeProperty("attributes", attr_view);
                    root.AppendObject(showview);
                }
            }



            return new NRemedy.MVC.UI.RawJsonResult()
            {
                Data = root.ToString(),
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
    }


    public class demoModel
    {
        public int total;
        public List<ToDoModel> rows;
    }
}
